<template>
  <view class="building-upgrade">
    <!-- 建筑信息区域 -->
    <view class="building-info">
      <image class="building-image" :src="building.image" mode="aspectFit"></image>
      <view class="building-details">
        <text class="building-name">{{building.name}} Lv.{{building.level}}</text>
        <text class="building-description">{{building.description}}</text>
      </view>
    </view>

    <!-- 升级所需资源显示 -->
    <view class="resource-requirements">
      <view class="resource-item" v-for="(amount, type) in upgradeRequirements" :key="type">
        <image class="resource-icon" :src="getResourceIcon(type)" mode="aspectFit"></image>
        <view class="resource-amount" :class="{ 'insufficient': !hasEnoughResource(type) }">
          <text>{{userResources[type] || 0}}</text>
          <text>/{{amount}}</text>
        </view>
      </view>
    </view>

    <!-- 升级进度条 -->
    <view v-if="isUpgrading" class="upgrade-progress">
      <view class="progress-bar">
        <view 
          class="progress-fill"
          :style="{ width: `${upgradeProgress}%` }"
        ></view>
      </view>
      <view class="time-remaining">
        <text>剩余时间: {{formatTimeRemaining}}</text>
        <button 
          class="speed-up-btn"
          @click="handleSpeedUp"
          :disabled="!canSpeedUp"
        >
          加速 (💎{{speedUpCost}})
        </button>
      </view>
    </view>

    <!-- 升级按钮 -->
    <button 
      class="upgrade-btn"
      :class="{ 'disabled': !canUpgrade }"
      @click="handleUpgrade"
      :disabled="!canUpgrade || isUpgrading"
    >
      <text v-if="!isUpgrading">升级</text>
      <text v-else>升级中...</text>
    </button>
  </view>
</template>

<script>
import { BUILDING_TYPES, SPEED_UP_ITEMS, UPGRADE_EVENTS } from '@/config/buildings.js'

export default {
  name: 'BuildingUpgrade',
  props: {
    building: {
      type: Object,
      required: true
    },
    userResources: {
      type: Object,
      required: true
    },
    userItems: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isUpgrading: false,
      upgradeProgress: 0,
      upgradeStartTime: null,
      upgradeDuration: 0,
      upgradeTimer: null,
      speedUpCost: 0,
      availableSpeedUps: []
    }
  },
  computed: {
    buildingType() {
      return BUILDING_TYPES[this.building.type] || BUILDING_TYPES.resource
    },
    upgradeRequirements() {
      const baseRequirements = {
        gold: this.building.level * 1000,
        wood: this.building.level * 500,
        stone: this.building.level * 300,
        iron: this.building.level * 200
      }
      
      // 根据建筑类型调整资源需求
      if (this.building.type === 'military') {
        Object.keys(baseRequirements).forEach(key => {
          baseRequirements[key] = Math.floor(baseRequirements[key] * 1.2)
        })
      }
      
      return baseRequirements
    },
    canUpgrade() {
      return Object.entries(this.upgradeRequirements).every(
        ([type, amount]) => (this.userResources[type] || 0) >= amount
      )
    },
    canSpeedUp() {
      return this.isUpgrading && (this.userResources.diamond || 0) >= this.speedUpCost
    },
    formatTimeRemaining() {
      if (!this.isUpgrading) return '00:00:00'
      const remaining = this.calculateTimeRemaining()
      const hours = Math.floor(remaining / 3600)
      const minutes = Math.floor((remaining % 3600) / 60)
      const seconds = remaining % 60
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
  },
  methods: {
    getResourceIcon(type) {
      const icons = {
        gold: '/static/icons/gold.png',
        wood: '/static/icons/wood.png',
        stone: '/static/icons/stone.png',
        iron: '/static/icons/iron.png'
      }
      return icons[type]
    },
    hasEnoughResource(type) {
      return (this.userResources[type] || 0) >= this.upgradeRequirements[type]
    },
    handleUpgrade() {
      if (!this.canUpgrade || this.isUpgrading) return
      
      this.isUpgrading = true
      this.upgradeProgress = 0
      this.upgradeStartTime = Date.now()
      
      // 根据建筑类型调整升级时间
      this.upgradeDuration = this.building.level * 60
      if (this.building.type === 'military') {
        this.upgradeDuration *= 1.5 // 军事建筑升级时间更长
      }
      
      this.speedUpCost = Math.ceil(this.upgradeDuration / 60)
      
      // 更新可用加速道具
      this.updateAvailableSpeedUps()
      
      this.startUpgradeTimer()
      
      // 触发升级开始事件
      UPGRADE_EVENTS.onStart(this.building)
      
      // 播放升级开始音效
      uni.createInnerAudioContext().src = '/static/sounds/upgrade-start.mp3'
      
      this.$emit('upgrade-start', {
        buildingId: this.building.id,
        resources: this.upgradeRequirements,
        duration: this.upgradeDuration
      })
    },
    
    updateAvailableSpeedUps() {
      this.availableSpeedUps = SPEED_UP_ITEMS.filter(item => 
        this.userItems[item.id] && this.userItems[item.id] > 0
      )
    },
    
    handleSpeedUp() {
      if (!this.canSpeedUp) return
      
      // 显示加速选项
      const options = [
        `钻石加速 (💎${this.speedUpCost})`,
        ...this.availableSpeedUps.map(item => `使用 ${item.name}`)
      ]
      
      uni.showActionSheet({
        itemList: options,
        success: (res) => {
          if (res.tapIndex === 0) {
            // 使用钻石加速
            this.$emit('speed-up', {
              buildingId: this.building.id,
              diamondCost: this.speedUpCost
            })
          } else {
            // 使用加速道具
            const selectedItem = this.availableSpeedUps[res.tapIndex - 1]
            this.$emit('use-speed-item', {
              buildingId: this.building.id,
              itemId: selectedItem.id
            })
          }
          
          this.completeUpgrade()
        }
      })
    },
    
    startUpgradeTimer() {
      this.upgradeTimer = setInterval(() => {
        const progress = this.calculateProgress()
        if (progress >= 100) {
          this.completeUpgrade()
        } else {
          this.upgradeProgress = progress
        }
      }, 1000)
    },
    calculateProgress() {
      const elapsed = (Date.now() - this.upgradeStartTime) / 1000
      return Math.min(100, (elapsed / (this.upgradeDuration * 60)) * 100)
    },
    calculateTimeRemaining() {
      if (!this.isUpgrading) return 0
      const elapsed = (Date.now() - this.upgradeStartTime) / 1000
      return Math.max(0, this.upgradeDuration * 60 - elapsed)
    },
    completeUpgrade() {
      clearInterval(this.upgradeTimer)
      this.isUpgrading = false
      this.upgradeProgress = 100
      
      // 触发升级完成事件
      const event = UPGRADE_EVENTS.onComplete(this.building)
      
      // 播放升级完成音效
      uni.createInnerAudioContext().src = '/static/sounds/upgrade-complete.mp3'
      
      this.$emit('upgrade-complete', {
        buildingId: this.building.id,
        event: event
      })
    }
  },
  beforeDestroy() {
    if (this.upgradeTimer) {
      clearInterval(this.upgradeTimer)
    }
  }
}
</script>

<style>
.building-upgrade {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.building-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.building-image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 10rpx;
}

.building-details {
  flex: 1;
}

.building-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.building-description {
  font-size: 26rpx;
  color: #666;
}

.resource-requirements {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30rpx;
}

.resource-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.resource-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.resource-amount {
  font-size: 24rpx;
  color: #333;
}

.resource-amount.insufficient {
  color: #ff4444;
}

.upgrade-progress {
  margin-bottom: 30rpx;
}

.progress-bar {
  height: 20rpx;
  background: #eee;
  border-radius: 10rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4CAF50, #8BC34A);
  transition: width 0.3s ease;
}

.time-remaining {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: #666;
}

.speed-up-btn {
  font-size: 24rpx;
  padding: 6rpx 20rpx;
  background: #FFD700;
  color: #333;
  border-radius: 30rpx;
  border: none;
}

.speed-up-btn:disabled {
  background: #ccc;
  color: #999;
}

.upgrade-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
}

.upgrade-btn.disabled {
  background: #ccc;
  color: #999;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.upgrade-btn:not(.disabled):active {
  animation: pulse 0.3s ease;
}
</style> 